﻿#include "StaticSecurityInterface.h"
#include <iostream>
#include "N_KAnalysis.h"
#include "BPAInterface.h"

#define STS_SUCCEED 0
#define STS_FAILED -1

namespace BPA{
    BPA_N_K_Analysis::BPA_N_K_Analysis(const char* database,
        int caseid,
        const std::vector<std::string>& Zone,
        const std::vector<double>& Voltage)
    {
        p_impl = new impl::N_KAnalysis();
        p_impl->caseid = caseid;
        p_impl->database = database;
        p_impl->Zone = Zone;
        p_impl->Voltage = Voltage;
    }

    BPA_N_K_Analysis::~BPA_N_K_Analysis()
    {
        if (p_impl)
        {
            delete p_impl;
            p_impl = nullptr;
        }
    }

    int BPA_N_K_Analysis::BPA_N_K_Configure()
    {
        p_impl->InitConfig();
        return STS_SUCCEED;
    }

    //静态N-1分析
    int BPA_N_K_Analysis::BPA_N_1_Analysis()
    {
        if (p_impl->N_1Analysis())
            return STS_SUCCEED;
        else
            return STS_FAILED;
    }

    //静态N-2分析
    int BPA_N_K_Analysis::BPA_N_2_Analysis()
    {
        p_impl->GetN_2Dats();
        if (p_impl->N_2Analysis())
            return STS_SUCCEED;
        else
            return STS_FAILED;
    }

    //静态N-3分析
    int BPA_N_K_Analysis::BPA_N_3Analysis()
    {
        p_impl->GetN_3Dats();
        if (p_impl->N_3Analysis())
            return STS_SUCCEED;
        else
            return STS_FAILED;
    }
}

int POWER_FLOW_DLLEXPORT N_1Calculate(std::string filename, JGG::filesystem::CDirectory work_dir)
{
    // TODO: 判断dat是否包含bse控制语句，若无则需添加

    string in_file = "dat_temp.dat";
    string out_file = "dat_temp_N-1.dat";

    // get .bse file
    DatWriteBack obj(database, caseid, Zone, Voltage, in_file, out_file);
    obj.GetN_1DatFromDb();
    CallPfnt(in_file);

    string pfo_file_path = "./bpa_temp/static_analysis_temp/dat_temp.pfo";
    BPAFilesIO::PfoParse pfoparser(database, caseid, pfo_file_path);
    pfoparser.N_1PfoParse();
    if (pfoparser.has_solution)
    {
        //执行BPA程序，N-1计算
        CallPfnt(out_file);
        pfo_file_path = "./bpa_temp/static_analysis_temp/dat_temp_N-1.pfo";
        pfoparser.pfofile = pfo_file_path;
        pfoparser.N_1PfoParse();
        if (pfoparser.has_solution)
        {
            Pfo2database(
                1,
                pfo_file_path,
                pfoparser.BaseOverInfo,
                pfoparser.BrekPro_BusInfo,
                pfoparser.BreakProInfo,
                pfoparser.NoneInfo);

            N_1PfoDataToPre();
            return true;
        }
        else
        {
            return NO_SOLUTION;
        }
    }
    else
    {
        return NO_SOLUTION;
    }
}

int POWER_FLOW_DLLEXPORT N_2Calculate(std::string filename, JGG::filesystem::CDirectory work_dir)
{

}

int POWER_FLOW_DLLEXPORT N_3Calculate(std::string filename, JGG::filesystem::CDirectory work_dir)
{

}